<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="150px" label-position="left">
    <el-form-item :label="$t('user.OldPassword')" prop="oldPassword">
      <el-input v-model="user.oldPassword" :placeholder="$t('user.InputOldPassword')" type="password" show-password />
    </el-form-item>
    <el-form-item :label="$t('user.NewPassword')" prop="newPassword">
      <el-input v-model="user.newPassword" :placeholder="$t('user.InputNewPassword')" type="password" show-password />
    </el-form-item>
    <el-form-item :label="$t('user.ConfirmPassword')" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" :placeholder="$t('user.SureConfirmPassword')" type="password"
        show-password />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="mini" @click="submit">{{
        $t("user.save")
      }}</el-button>
      <el-button type="danger" size="mini" @click="close">{{
        $t("role.Close")
      }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import {
    updatePassword
  } from "@/api/system/user-profile";

  export default {
    data() {
      const equalToPassword = (rule, value, callback) => {
        if (this.user.newPassword !== value) {
          callback(new Error(this.$t("user.DifferentPassword")));
        } else {
          callback();
        }
      };
      return {
        user: {
          oldPassword: undefined,
          newPassword: undefined,
          confirmPassword: undefined,
        },
        // 表单校验
        rules: {
          oldPassword: [{
            required: true,
            message: this.$t("user.OldPasswordNull"),
            trigger: "blur",
          }, ],
          newPassword: [{
              required: true,
              message: this.$t("user.NewPasswordNull"),
              trigger: "blur",
            },
            {
              min: 6,
              max: 20,
              message: this.$t("user.Long6-20"),
              trigger: "blur",
            },
          ],
          confirmPassword: [{
              required: true,
              message: this.$t("user.ConfirmPasswordNULL"),
              trigger: "blur",
            },
            {
              required: true,
              validator: equalToPassword,
              trigger: "blur"
            },
          ],
        },
      };
    },
    methods: {
      submit() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            updatePassword(this.user.oldPassword, this.user.newPassword).then(
              (response) => {
                this.$modal.msgSuccess(this.$t("ModifySuccessful"));
              }
            );
          }
        });
      },
      close() {
        this.$tab.closePage();
      },
    },
  };

</script>
